package com.hut.oa.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hut.oa.model.bean.Menu;
import com.hut.oa.model.bean.Role;
import com.hut.oa.model.dao.role.RoleDao;
import com.hut.oa.model.dao.system.MenuDao;
import com.hut.oa.service.SystemService;

@Controller
@RequestMapping("/role")
public class RoleController {
	
	@Autowired
	RoleDao rd;
	
	@Autowired
	SystemService ss;
	
	@Autowired
	MenuDao md;
	
	/**
	 * 到角色列表页面
	 * @return
	 */
	@RequestMapping
	public String toRole(Model model,@PageableDefault(value=10,sort={"powerValue"},direction=Direction.DESC) Pageable pageable){
		model.addAttribute("roles", rd.findAll(pageable));
		return "role/role";
	}
	
	/**
	 * 到角色表单界面
	 * @return
	 */
	@RequestMapping("/add")
	public String toRoleAdd(@RequestParam(required=false,name="id")Long id,Model model){
		if(id!=null){
			model.addAttribute("role", rd.findById(id));
		}
		return "role/addRole";
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public void saveRole(Role role){
		rd.save(role);
	}
	
	/**
	 * 为角色分配权限
	 * @param id
	 * @param ids
	 */
	@RequestMapping("/resource")
	@ResponseBody
	public void saveResource(@RequestParam("id")Long id,@RequestParam("ids")Long[] ids){
		List<Menu> menus=new ArrayList<>();
		for (int i = 0; i < ids.length; i++) {
			menus.add(md.findById(ids[i]));
		}
		Role role=rd.findById(id);
		role.setMenus(menus);
		rd.save(role);
	}
	
}
